package com.endava.graduates.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.endava.graduates.model.User;

@Repository
public class UserDaoImpl implements UserDao {

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public User getUserById(Integer id) {

		String sql = "select first_name, last_name from users where user_id = ?";
		// Map namedParameters = Collections.singletonMap("user_id", id);
		//
		// RowMapper<User> mapper = new RowMapper<User>() {
		// public User mapRow(ResultSet rs, int rowNum) throws SQLException {
		// User user = new User();
		// user.setFirstName(rs.getString("first_name"));
		// user.setLastName(rs.getString("last_name"));
		// return user;
		// }
		// };

		return (User) jdbcTemplate.queryForObject(sql, new Object[] { id },
				new UserMapper());
	}

	@Override
	public User getUserByUsername(String username) {

		String sql = "select first_name, last_name, username, password from users where username = ?";
		User user = null;
		
		try{
			user = (User) jdbcTemplate.queryForObject(sql,
				new Object[] { username }, new UserMapper());
			return user;
		}catch(EmptyResultDataAccessException e){return null;}
		
	}

	@Override
	public List<User> getUsers() {
		return this.jdbcTemplate.query(
				"select first_name, last_name, username, password from users",
				new UserMapper());
	}

	private static final class UserMapper implements RowMapper<User> {
		public User mapRow(ResultSet rs, int rowNum) throws SQLException {

			User user = null;
			if (rs.first()) {

				user = new User();
				user.setFirstName(rs.getString("first_name"));
				user.setLastName(rs.getString("last_name"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));

			}
			return user;
		}

	}

}